package top.zhangjianyong.tools.generation;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhangjianyong
 * @since 2025/3/20 下午1:40
 */
@Slf4j
@Component
public class GenerationCaller {
    @Value("${qwen.api-key}")
    private String apiKey;


    public GenerationResult callWithMessage(List<Message> messages) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-turbo")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }

    public GenerationResult callWithMessage(Message message) throws ApiException, NoApiKeyException, InputRequiredException {
        Message systemMsg = GenerationMessage.createSystemMessage();
        return callWithMessage(Arrays.asList(systemMsg, message));
    }


}
